/**
 * 
 */
package com.music.profile.controller;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.music.core.members.beans.Member;
import com.music.core.members.service.MemberService;


/**
 * @author spradeep
 *
 */
public class GoogleLoginController extends AbstractController {
	private static final Logger log = Logger.getLogger(GoogleLoginController.class.getName());
	private MemberService memberService;
	
	public MemberService getMemberService() {
		return memberService;
	}
	@Required
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.ser	vlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		log.info("Trying to get current Google user");
		if(user!=null) {
			log.info("User logged in Google: "+user.toString());
			// Is the user already registered? 
			Member member = memberService.getMember(user.getEmail());
			if(member== null) {
				log.info("Creating New user:");
				// No. Create a new member
				String nickname = user.getNickname();
				// Remove '@domain.com' from the nick name
				String firstName = nickname.split("@")[0];
				member = memberService.createMember(firstName, "", null, null, null, user.getEmail());
			} else {
				log.info("Google User already registered");
			}
			req.setAttribute("member", member);
			return new ModelAndView("loginSuccess");
		} 
		// Now redirect the user to google login page with return url as the current url.
		res.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		return null; // Control will never come here due to the redirect at the top.
	}

}
